<?php


namespace jp\Weather\Weather;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\InvalidArgumentException;
use jp\Weather\Weather\exceptions\Exception;
use jp\Weather\Weather\exceptions\HttpException;

class Weather
{
    protected $key = 'da695120cf7444712bd46976e2b54e4e';
    protected $guzzleOptions = [];

    public function __construct($key)
    {
        $this->key = $key;      //天气预报key
    }

    public function getHttpClient(): Client
    {
        return new Client($this->guzzleOptions);
    }

    /**
     * 自定义guzzle参数
     * @param array $options
     */
    public function setGuzzleOptions(array $options)
    {
        $this->guzzleOptions = $options;
    }


    /**
     * 获取天气预报接口
     * @param $city
     * @param string $type
     * @param string $format
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getWeather($city, string $type = '', string $format = 'json'): string
    {
        $url = 'https://restapi.amap.com/v3/weather/weatherInfo';
        if (!in_array(strtolower($format), ['xml', 'json'])) {
            throw new InvalidArgumentException("参数错误");
        }
        if (!in_array(strtolower($type), ['base', 'all'])) {
            throw new InvalidArgumentException('Invalid type value(base/all): ' . $type);
        }
        $query = array_filter([
            'key' => $this->key,
            'city' => $city,
            'output' => $format,
            'extensions' => $type,
        ]);
        try {
            $response = $this->getHttpClient()->get($url, [
                'query' => $query
            ])->getBody()->getContents();
            return 'json' === $format ? json_decode($response, true) : $response;

        } catch (Exception $exception) {
            throw new HttpException($exception->getMessage(), $exception->getCode(), $exception);
        }

    }
}